import os

def get_ignored_folders(folder_path):
    # 获取指定文件夹路径下被忽略的文件夹列表
    gitignore_path = os.path.join(folder_path, '.gitignore')
    ignored_folders = [] # 初始化被忽略的文件夹列表

    if os.path.exists(gitignore_path):
        with open(gitignore_path, 'r',encoding='utf-8') as gitignore_file:
            lines = gitignore_file.readlines()
            ignored_folders = [line.strip() for line in lines if not line.startswith('#') and line.strip() != '']

    return ignored_folders # 返回被忽略的文件夹列表

def generate_readme(folder_path, indent=0, ignored_folders=None):
    if ignored_folders is None:
        ignored_folders = []

    entries = os.listdir(folder_path)
    
    # 筛选出 Markdown 文件和子文件夹
    print('筛选',folder_path)
    markdown_files = [f for f in entries if f.endswith('.md')]
    subdirectories = [d for d in entries if os.path.isdir(os.path.join(folder_path, d))]
    
    # 检查是否应该忽略当前文件夹
    if os.path.basename(folder_path) in ignored_folders:
        return []

    # 如果文件夹中有 Markdown 文件，则生成链接，否则返回空列表
    if markdown_files:
        # 构建当前目录的 Markdown 链接列表、文件夹名字和子文件夹的 README 链接
        folder_name = "{}- {}".format("  " * indent, os.path.basename(folder_path).replace(" ", "-"))
        markdown_links = ["{}- [{}]({})".format("  " * (indent + 1), file.replace(" ", "-"), os.path.join(folder_path, file).replace(" ", "-")) for file in markdown_files]
        subfolder_readmes = [generate_readme(os.path.join(folder_path, subdir), indent + 1, ignored_folders) for subdir in subdirectories]
        
        # 递归处理子文件夹
        for subdir_readme in subfolder_readmes:
            markdown_links.extend(subdir_readme)
        
        return [folder_name] + markdown_links
    else:
        return []

# 用法示例
folder_path = './'  # 输出目录为当前工作目录
ignored_folders = get_ignored_folders(folder_path)
markdown_links = generate_readme(folder_path, ignored_folders=ignored_folders)

# 兼容 Windows 平台，生产无\的路径
no_win_dirs = [item.replace('\\', '/') for item in markdown_links]

# 替换为的新字符,输入git远程仓库地址
new_char = 'https://gitee.com/zhouyanyu/note/blob/master/'

# 使用列表推导式和字符串的 replace 方法进行替换
new_markdown_list = [item.replace('./', new_char) for item in no_win_dirs]
# README的名字
readme_name = '# 我的笔记目录'
# README的内容
readme_text = ''
# 构建 README 内容
# 删除第一个空元素
del(new_markdown_list[0])
# 拼接标题、内容、其他内容
readme_content = readme_name + "\n\n" + "\n".join(new_markdown_list) + readme_text

# 将内容写入 README.md 文件（指定编码为 UTF-8，放在当前工作目录下）
print('\n 将内容写入 README.md 文件')
with open(os.path.join(folder_path, 'README.md'), 'w', encoding='utf-8') as readme_file:
    readme_file.write(readme_content)
